//登录注册的路由

let express = require('express')

let router = express.Router()

// 引入md5 加密模块
var md5=require('md5-node')

let {query} = require('../utils/db.js')



router.get('/logout',(req,res)=>{
    // session.user
    req.session.user = null
    res.redirect('/article/index')
})
// 登录注册

// 显示登录页面
router.get('/login',(req,res)=>{
    res.render('loginreg/login.ejs')
})

router.post('/login',(req,res)=>{

    let username = req.body.username
    let password = md5(req.body.password)
    let sql = `select * from users where username='${username}' and password='${password}'`
    query(sql,(data)=>{
        
        if( data.length !=0 ){//用户名密码正确

            //删除密码
            delete data[0].password
            req.session.user = data[0]

            req.flash('success','登录成功')
            res.redirect('/article/index')
        }else{
            req.flash('error','用户名或密码错误')
            res.redirect('/user/login')
        }
        
    })
    // res.render('login.ejs')
})

//显示注册页面
router.get('/reg',(req,res)=>{
    
    res.render('loginreg/reg.ejs')
})
// post请求实现注册
router.post('/reg',(req,res)=>{
    let user = req.body
    let username = user.username
    let password = md5(user.password)
    let sql = `insert into users (username,password) values ('${username}','${password}')`
    
    query(sql,(data)=>{
        res.redirect('/user/login')
    })
})

module.exports = router